package com.cy.mall.comm.aspect;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cy.mall.comm.utils.CommonUtils;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.model.PageBean;

import lombok.extern.slf4j.Slf4j;

/**
 * 切面日志
 *
 * @author tanyilin
 *
 * @create 2019年1月22日 下午5:46:47
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

	@Pointcut("execution(public * com.cy.mall.web..*.*(..))")
	public void webLog() {
		
	}
	
	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		log.info("doBefore==========》 ");
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		
		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + CommonUtils.getIpAddress(request));
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
	}
	
//	@Around("webLog()")
//	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
//		log.info("doAround1==========》 ");
//		// 接收到请求，记录请求内容
//		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//		
//		HttpServletRequest request = attributes.getRequest();
//		HttpServletResponse response = attributes.getResponse();
//		
//		String methodName = joinPoint.getSignature().getName();
//		
//		if("xiaoanCreditCheckNotify".equals(methodName)) {
//			request.getRequestDispatcher("/").forward(request, response);
//			return null;
//		}
//		
//		Object obj = joinPoint.proceed();
//		log.info("doAround2==========》 ");
//		
//		return obj;
//	}
	
	@AfterReturning(returning = "ret", pointcut = "webLog()")
	public void doAfterReturning(Object ret) throws Throwable {
		log.info("doAfterReturning==========》 ");
		boolean flag = ret instanceof PageBean;
		if(!flag) {
			// 处理完请求，返回内容
			log.info("RESPONSE : " + JsonObjectMapper.toJson(ret));
		}
	}
}
